package test.administrator.example.com.mvptest1.framework.support;

/**
 * Created by thinkpad on 2018/7/18.
 */

import test.administrator.example.com.mvptest1.framework.MvpPresenter;
import test.administrator.example.com.mvptest1.framework.MvpView;

/**
 * 代理模式->第二重代理->代理对象->绑定和解绑
 * 两个特点
 * 特点一：实现目标接口（可有可无）
 * 特点二：持有目标对象引用（必需）
 *
 * @param <V>
 * @param <P>
 */
public class ProxyMvpDelegateCallback<V extends MvpView, P extends MvpPresenter<V>> implements MvpDelegateCallback<V, P> {

	//特点二：持有目标对象引用（必需）->mvpCallback（实际上->MvpActivity）
	private MvpDelegateCallback<V, P> mvpCallback;

	public ProxyMvpDelegateCallback(MvpDelegateCallback<V, P> mvpCallback) {
		this.mvpCallback = mvpCallback;
	}

	@Override
	public P createPresenter() {
		P presenter = this.mvpCallback.getPresenter();
		if (presenter == null) {
			presenter = this.mvpCallback.createPresenter();
		}
		if (presenter == null) {
			throw new NullPointerException("P层不能为空");
		}
		this.mvpCallback.setPresenter(presenter);
		return presenter;
	}

	@Override
	public P getPresenter() {
		return this.mvpCallback.getPresenter();
	}

	@Override
	public void setPresenter(P presenter) {
		this.mvpCallback.setPresenter(presenter);
	}

	@Override
	public V getMvpView() {
		return this.mvpCallback.getMvpView();
	}

	/**
	 * 添加两个重要的方法
	 */
	public void attachView() {
		getPresenter().attachView(getMvpView());
	}

	public void detachView() {
		getPresenter().detachView();
	}

}
